package cn.matrix42.potoo.jdbc.dialect.postgres;

import cn.matrix42.potoo.jdbc.dialect.AbstractDialect;

import java.util.Arrays;
import java.util.Optional;
import java.util.stream.Collectors;

public class PostgresDialect extends AbstractDialect {

    private static final String DRIVER = "org.postgresql.Driver";
    private static final String URL_PATTERN = "jdbc:postgresql://%s:%d/%s";

    @Override
    public String dialectName() {
        return "PostgreSQL";
    }

    @Override
    public String getLimitClause(long limit) {
        return "LIMIT " + limit;
    }

    @Override
    public String quoteIdentifier(String identifier) {
        return identifier;
    }

    @Override
    public Optional<String> getUpsertStatement(
        String tableName, String[] fieldNames, String[] uniqueKeyFields) {
        String uniqueColumns =
            Arrays.stream(uniqueKeyFields)
                .map(this::quoteIdentifier)
                .collect(Collectors.joining(", "));
        String updateClause =
            Arrays.stream(fieldNames)
                .map(f -> quoteIdentifier(f) + "=EXCLUDED." + quoteIdentifier(f))
                .collect(Collectors.joining(", "));
        return Optional.of(
            getInsertIntoStatement(tableName, fieldNames)
                + " ON CONFLICT ("
                + uniqueColumns
                + ")"
                + " DO UPDATE SET "
                + updateClause);
    }

    @Override
    public String getDriver() {
        return DRIVER;
    }

    @Override
    public String getUrlPattern() {
        return URL_PATTERN;
    }
}
